package response

import (
	"encoding/json"
	"log"
	"net/http"
)

// Response 统一响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// 响应状态码常量
const (
	CodeSuccess       = 200
	CodeBadRequest    = 400
	CodeNotFound      = 404
	CodeInternalError = 500
)

// Success 成功响应
func Success(w http.ResponseWriter, data interface{}) {
	response := Response{
		Code:    CodeSuccess,
		Message: "success",
		Data:    data,
	}
	writeJSON(w, http.StatusOK, response)
}

// SuccessWithMessage 带消息的成功响应
func SuccessWithMessage(w http.ResponseWriter, message string, data interface{}) {
	response := Response{
		Code:    CodeSuccess,
		Message: message,
		Data:    data,
	}
	writeJSON(w, http.StatusOK, response)
}

// BadRequest 400错误响应
func BadRequest(w http.ResponseWriter, message string) {
	response := Response{
		Code:    CodeBadRequest,
		Message: message,
	}
	writeJSON(w, http.StatusBadRequest, response)
}

// NotFound 404错误响应
func NotFound(w http.ResponseWriter, message string) {
	response := Response{
		Code:    CodeNotFound,
		Message: message,
	}
	writeJSON(w, http.StatusNotFound, response)
}

// InternalError 500错误响应
func InternalError(w http.ResponseWriter, message string) {
	response := Response{
		Code:    CodeInternalError,
		Message: message,
	}
	writeJSON(w, http.StatusInternalServerError, response)
}

// Error 通用错误响应
func Error(w http.ResponseWriter, httpStatus int, code int, message string) {
	response := Response{
		Code:    code,
		Message: message,
	}
	writeJSON(w, httpStatus, response)
}

// writeJSON 写入JSON响应
func writeJSON(w http.ResponseWriter, httpStatus int, response Response) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(httpStatus)

	if err := json.NewEncoder(w).Encode(response); err != nil {
		log.Printf("Failed to encode JSON response: %v", err)
		// 如果JSON编码失败，写入纯文本错误
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Internal server error"))
	}
}

// WriteText 写入纯文本响应（保持向后兼容）
func WriteText(w http.ResponseWriter, httpStatus int, message string) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(httpStatus)
	w.Write([]byte(message))
}
